package com.qf.votedemo.contestant.controller;

import cn.hutool.jwt.JWT;
import com.qf.votedemo.contestant.entity.Contestant;
import com.qf.votedemo.contestant.entity.Ticket;
import com.qf.votedemo.contestant.service.IContestantService;
import com.qf.votedemo.contestant.service.IContestantphoneService;
import com.qf.votedemo.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lx
 * @since 2023-02-24
 */
@RestController
@RequestMapping("/contestant")
@CrossOrigin
@Slf4j
public class ContestantController {


    @Autowired
    private IContestantService contestantService;


    @Autowired
    private IContestantphoneService contestantphoneService;


    /**
     * 投票
     *
     * @param phoneNum     电话号码
     * @param contestantId 选手ID
     * @return
     */
    @RequestMapping("/ballot")
    public ResultVo ballot(String phoneNum, Integer contestantId, @RequestHeader("token") String token) throws Exception {
        log.debug("接收到的参数为phoneNum={},contestant={},token={}", phoneNum, contestantId, token);
        //验证投票时token是否过期
        boolean validate = JWT.of(token).setKey("qfjava2203".getBytes(StandardCharsets.UTF_8)).validate(0);
        if (!validate) {
            ResultVo ok = ResultVo.ok();
            ok.put("msg", "token已过期,请重新颁发token");
            ok.put("code", 1001);
            return ok;
        }
        contestantService.vote(phoneNum, contestantId);
        return ResultVo.ok();
    }

    @RequestMapping("/getTicket")
    public ResultVo getTicket() {
        List<Ticket> tickets = contestantphoneService.getTicket();
        ResultVo ok = ResultVo.ok();
        ok.put("data", tickets);
        return ok;
    }

    @RequestMapping("/ballotRedis")
    public ResultVo ballotRedis(String phoneNum, Integer contestantId, @RequestHeader("token") String token) throws Exception {
        log.debug("接受到的参数为phoneNum={},contestantId={},token={}", phoneNum, contestantId, token);
        contestantService.voteRedis(phoneNum, contestantId, token);
        return ResultVo.ok();
    }

    @RequestMapping("/getTicketRedis")
    public ResultVo getTicketRedis() {
        // 读取DB中选手表存入缓存
        List<Ticket> tickets = contestantphoneService.getTicketRedis();
        ResultVo ok = ResultVo.ok();
        ok.put("data", tickets);
        return ok;
    }

    @RequestMapping("/contestantSaveRedis")
    public void contestantSaveRedis(){
        // 读取DB中选手表存入缓存
        contestantService.getContestants();
    }

}
